﻿using LDM.Framework.ExceptionHandling;
using LDM.Framework.ExceptionHandling.Extensions;
using LDM.Sys.Repository.Interfaces;
using LDM.Sys.Repository.Repository;
using LDM.Sys.Service.Controllers.Base;
using LDM.Sys.ServiceAPI.Model.DBModel;
using LDM.Sys.ServiceAPI.Model.Enum;
using LDM.Sys.ServiceAPI.Model.ViewModel.Request.AuthorityReq;
using LDM.Sys.ServiceAPI.Model.ViewModel.Response.Menu;
using Microsoft.AspNetCore.Mvc;
using Model.Models;
using Utility.Extensions;
using Utility.Utils;
using Session = Model.Session;

namespace LDM.Sys.Service.Controllers.Authority
{
    /// <summary>
    /// 菜单服务
    /// </summary>
    public class MenuController : BaseController
    {
        private readonly ISysMenuRepository _menuRepository;
        private readonly ISysUserRoleRelRepository _userRoleRelRepository;
        private readonly ISysRoleRepository _roleRepository;
        private readonly ISysRoleAuthorityRelRepository _roleAuthorityRelRepository;
        private readonly Session _session;
        /// <summary>
        /// 构造函数
        /// </summary>
        public MenuController(ISysMenuRepository menuRepository,
             Session session,
             ISysRoleAuthorityRelRepository roleAuthorityRelRepository,
             ISysRoleRepository roleRepository,
             ISysUserRoleRelRepository userRoleRelRepository)
        {
            _menuRepository = menuRepository;
            _session = session;
            _roleAuthorityRelRepository = roleAuthorityRelRepository;
            _roleRepository = roleRepository;
            _userRoleRelRepository = userRoleRelRepository;
        }

        /// <summary>
        /// 获取当前用户菜单
        /// </summary>
        [HttpPost]
        public List<UserMenuViewRes> GetCurrentUserMenu()
        {
            List<UserMenuViewRes> result = new();
            if (_session.UserId == 0)
                throw new BusinessException($"用户错误");
            var userRoles = _userRoleRelRepository.GetUserRoles(_session.UserId);
            if (!userRoles.Any())
                return result;
            var roleIds = userRoles.Select(x => x.RoleId).ToList();
            var roleAuthoritys = _roleAuthorityRelRepository.GetuthorityMenuByRoleIds(roleIds);
            if (!roleAuthoritys.Any())
                return result;
            return GetMenu(0);
            List<UserMenuViewRes> GetMenu(int pid)
            {
                var menuView = new List<UserMenuViewRes>();
                var pRoleAuthoritys = roleAuthoritys.Where(x => x.PMenuId == pid).ToList();
                if (!pRoleAuthoritys.Any())
                    return null;
                foreach (var roleAuthority in pRoleAuthoritys)
                {
                    UserMenuViewRes userMenu = new();
                    userMenu.pMenuId = roleAuthority.PMenuId;
                    userMenu.menuId = roleAuthority.MenuId;
                    userMenu.iconCls = roleAuthority.Icon;

                    if (roleAuthority.MenuType == (int)MenuTypeEnum.Menu)
                    {
                        userMenu.text = roleAuthority.MenuName;
                    }
                    else
                    {
                        userMenu.text = $" <a class=\"nav\" rel=\"{roleAuthority.Url}\" style=\"text-decoration:none;\" onclick='addTab(\"{roleAuthority.MenuName}\", \"{roleAuthority.Url}\", \"{roleAuthority.Icon}\")' >{roleAuthority.MenuName} </a>";
                    }
                    userMenu.children = GetMenu(roleAuthority.MenuId);
                    menuView.Add(userMenu);
                }
                return menuView;
            }
        }

        /// <summary>
        /// 设置角色菜单
        /// </summary>
        /// <param name="request"></param>
        [HttpPost]
        public void SetRoleMenu(SetRoleMenuReq request)
        {
            request.ThrowIfNull()
                   .ThrowIf(x => x.MenuId <= 0, "请输入正确的菜单")
                   .ThrowIf(x => x.RoleIds.Any(), "角色ID不能为空");
            var menu = _menuRepository.GetByKey(request.MenuId);
            menu.ThrowIfNull("菜单不存在");

            var roleAuthoritys = _roleAuthorityRelRepository.GetAuthorityByAuthorityIds(new List<int>() { request.MenuId }, AuthorityTypeEnum.Menu);
            if (roleAuthoritys.Any())
            {
                ///TODO:此处为批量插入数据
                _roleAuthorityRelRepository.Insert(roleAuthoritys);
            }
            var roleAuthorityRels = request.RoleIds.Select(x => new SysRoleAuthorityRel
            {
                RoleId = request.MenuId,
                AuthorityId = x,
                AuthorityType = (int)AuthorityTypeEnum.Menu
            }).ToList();
            _roleAuthorityRelRepository.Insert(roleAuthorityRels);
        }

        #region 基础菜单
        /// <summary>
        /// 获取菜单列表
        /// </summary>
        [HttpPost]
        public List<SysMenu> GetSysMenus()
        {
            return _menuRepository.GetSysMenus();
        }

        /// <summary>
        /// 添加菜单
        /// </summary>
        [HttpPost]
        public void AddSysMenu(AddSysMenuReq request)
        {
            request.ThrowIfNull();
            var obj = request.Copy<AddSysMenuReq, SysMenu>();
            obj.MenuCode = IdUtil.NewIdByTimeX34(SceneCodePrefix.MenuCode);
            _menuRepository.Insert(obj);
        }

        /// <summary>
        /// 修改菜单
        /// </summary>
        [HttpPost]
        public void UpdateSysMenu(UpdateSysMenuReq request)
        {
            request.ThrowIfNull().ThrowIf(x => x.Id == 0, "请传入Id");
            var menu = _menuRepository.GetByKey(request.Id);
            menu.ThrowIfNull("当前菜单不存在");
            var obj = request.Copy<UpdateSysMenuReq, SysMenu>(false);
            _menuRepository.Update(obj);
        }

        /// <summary>
        /// 删除菜单
        /// </summary>
        [HttpPost]
        public void DelSysMenu(DelSysMenuReq request)
        {
            request.ThrowIfNull().ThrowIf(x => x.Id == 0, "请传入Id");
            var menu = _menuRepository.GetByKey(request.Id);
            menu.ThrowIfNull("当前菜单不存在");
            _menuRepository.Delete(request.Id);
        }
        #endregion
    }
}
